/**
 * 内容管理 - 文章管理
 */

import React from 'react'
import PropTypes from 'prop-types'
import {connect} from 'dva'
import {Page} from 'components'
import {routerRedux} from 'dva/router'
import {Row, Col, Button, Popconfirm, notification, Icon, Tabs} from 'antd'
import queryString from 'query-string'

import ArticleTable from './components/ArticleTable'
import ArticlePubTable from './components/ArticlePubTable'
import ArticleFilter from './components/ArticleFilter'
import ArticlePubFilter from './components/ArticlePubFilter'
import ArticleModal from './components/ArticleModal'
import ArticlePubModal from './components/ArticlePubModal'

import style from './article.less'

// TODO 文件上传URL，需要从配置文件中获取
// import {config} from '../../../utils'
// const {uploadFile} = config.api.upload.uploadFile
const currentIpPort = 'http://127.0.0.1:9998'
const uploadFileUrl = currentIpPort + '/upload/uploadFile'

const ContentArticle = ({
                          location, dispatch, contentArticle, loading,
                        }) => {

  const {query, getArticlePubModel, pathname} = location
  const {
    list,
    list2,
    pagination,
    currentItem,
    modalVisible,
    modalType,
    currentItemEditor,
    editorVisible,
    isMotion,
    selectedRowKeys,
    selectedRowKeysPub,
    htmlContent,
    PubmodalVisible,
    editContentId,
    editInitialContent,
    editContentFormat,
    editHtmlContent,
    editEditorInstance,
    pubfilterProps,
    isPubModal,
    modalPubTreeDataToWho,
    modalPubTreeDataAddress,

  } = contentArticle

  // 刷新事件
  const handleRefresh = (newQuery) => {
    dispatch(routerRedux.push({
      pathname,
      search: queryString.stringify({
        ...query,
        ...newQuery,
      }),
    }))
  }
  const handleRefresh2 = (newQuery) => {
    // dispatch(routerRedux.push({
    //   pathname,
    //   search: queryString.stringify({
    //     ...getArticlePubModel,
    //     ...newQuery,
    //   }),
    // }))
    dispatch({
      type: 'contentArticle/getArticlePubModel',
      payload:{ ...newQuery },
    })
  }

  const modalProps = {
    item: modalType === 'create' ? {} : currentItem,
    visible: modalVisible,
    maskClosable: false,
    confirmLoading: loading.effects[`contentArticle/${modalType}`],
    title: `${modalType === 'create' ? '创建文章' : '编辑文章'}`,
    okText: "确认",
    cancelText: "取消",
    // wrapClassName: 'vertical-center-modal',
    wrapClassName: style["article-editor-modal"],
    onOk (data) {
      data.content = editHtmlContent
      dispatch({
        type: `contentArticle/${modalType}`,
        payload: data,
      })
        .then(() => {
          handleRefresh()
        })
    },
    onCancel () {
      dispatch({
        type: 'contentArticle/hideModal',
      })
    },
    editorProps: {
      serverURL: uploadFileUrl,
      editContentId: modalType === 'create' ? editContentId : currentItem['id'],
      editInitialContent: modalType === 'create' ? editInitialContent : currentItem['content'],
      // editHtmlContent: modalType === 'create' ? editHtmlContent : currentItem['content'],
      editHtmlContent: (() => {
        if (modalType === 'create') {
          return editHtmlContent
        }
        if (modalType === 'update') {

          return currentItem['content'].replace(new RegExp("_ant_page_ip_port_", "g"), currentIpPort)
        }
      })(),
      // 内容改变
      onHTMLChange: (htmlContent) => {
        dispatch({
          type: 'contentArticle/editorContentUpdate',
          payload: {
            editHtmlContent: htmlContent,
          },
        })
      },
    },
  }

  const listProps = {
    isPubModal,
    dataSource: list,
    loading: loading.effects['contentArticle/query'],
    pagination,
    location,
    isMotion,
    onChange (page) {
      handleRefresh({
        page: page.current,
        pageSize: page.pageSize,
      })
    },
    // 删除
    onDeleteItem (id) {
      dispatch({
        type: 'contentArticle/delete',
        payload: id,
      })
        .then(() => {
          handleRefresh({
            page: (list.length === 1 && pagination.current > 1) ? pagination.current - 1 : pagination.current,
          })
        })
    },
    // 编辑
    onEditItem (item) {
      dispatch({
        type: 'contentArticle/showModal',
        payload: {
          modalType: 'update',
          currentItem: item,
        },
      })
    },
    rowSelection: {
      selectedRowKeys,
      onChange: (keys) => {
        dispatch({
          type: 'contentArticle/updateState',
          payload: {
            selectedRowKeys: keys,
          },
        })
      },
    },
    // 发布状态修改
    onShowPubModal (item) {
      dispatch({
        type: 'contentArticle/switchArticlePubModal',
      })
    },
    // 取消发布
    onRemovePub (item) {
      // TODO remove pub

      dispatch({
        type: 'contentArticle/switchArticlePubModal',
      })
    },
  }

  const listProps2 = {
    isPubModal,
    dataSource: list2,
    loading: loading.effects['contentArticle/getArticlePubModel'],
    pagination,
    location,
    isMotion,
    onChange (page) {
      handleRefresh({
        page: page.current,
        pageSize: page.pageSize,
      })
    },
    // 删除
    onDeleteItemPub (data) {
      dispatch({
        type: 'contentArticle/deletePub',
        payload: data,
      })
        .then(() => {
          handleRefresh2({
            page: (list2.length === 1 && pagination.current > 1) ? pagination.current - 1 : pagination.current,
          })
        })
    },
    // 编辑
    onEditItem (item) {
      dispatch({
        type: 'contentArticle/showModal',
        payload: {
          modalType: 'update',
          currentItem: item,
        },
      })
    },
    rowSelection: {
      selectedRowKeysPub,
      onChange: (keys) => {
        dispatch({
          type: 'contentArticle/updateState',
          payload: {
            selectedRowKeysPub: keys,
          },
        })
      },
    },
  }

  // 查询部分参数
  const filterProps = {
    isMotion, // 显示内容切换
    selectedRowKeys, // 选中行数
    filter: {
      ...query,
    },
    onFilterChange (value) {
      handleRefresh({
        ...value,
        page: 1,
      })
    },
    // 新建
    onAdd () {
      dispatch({
        type: 'contentArticle/showModal',
        payload: {
          modalType: 'create',
          currentItem: {}, // 新建时清空数据
        },
      })
    },
  }

  const filterProps2 = {
    isMotion, // 显示内容切换
    selectedRowKeysPub, // 选中行数
    filter: {
      ...query,
    },
    onFilterChange (value) {
      handleRefresh2({
        ...value,
        page: 1,
      })
    },
  }

  //发布模态
  const modalPubProps = {
    visible: PubmodalVisible,
    modalPubTreeDataToWHo: modalPubTreeDataToWho,
    modalPubTreeDataAddress: modalPubTreeDataAddress,
    maskClosable: false,
    loading: loading.effects[`contentArticle/getPub`],
    confirmLoading: loading.effects[`contentArticle/addPub`],
    title: '请选择要发布的单位及频道',
    okText: "确认",
    cancelText: "取消",
    // wrapClassName: 'vertical-center-modal',
    wrapClassName: style["link-pub-modal"],

    // TODO 文章发布：目标、页面位置 参数
    onOk (data) {

      dispatch({
        type: `contentArticle/insertPubArticleModel`,
        payload: {
          coCode: data.toWho[1],
          pgPletId: data.address[1],
          articleId: selectedRowKeys,
        },
      })
        .then(() => {
          handleRefresh()
        })
    },
    onCancel () {
      dispatch({
        type: 'contentArticle/hidePubModal',
      })
    },
    onCheck (checkedKeys) {
      console.log(checkedKeys)
      dispatch({
        type: 'contentArticle/showPubModal',
        payload: {
          modalPubTreeData: checkedKeys,
        },
      })
    },
  }

  // 弹出文章发布modal，首先查询单位及portlet信息
  const onPub = () => {
    dispatch({
      type: 'contentArticle/getPub',
    })
  }

  const handleDeleteItems = () => {
    dispatch({
      type: 'contentArticle/multiDelete',
      payload: {
        ids: selectedRowKeys,
      },
    })
      .then(() => {
        handleRefresh({
          page: (list.length === selectedRowKeys.length && pagination.current > 1) ? pagination.current - 1 : pagination.current,
        })
      })
  }
  // 批量删除已发布的文章记录---youwenti
  const handleDeletePubItems = () => {
    dispatch({
      type: 'contentArticle/multiDeletePub',
      payload: {
        ids: selectedRowKeys,
      },
    })
      .then(() => {
        handleRefresh({
          page: (list.length === selectedRowKeys.length && pagination.current > 1) ? pagination.current - 1 : pagination.current,
        })
      })
  }

  const handleTabsChange = (activeKey) => {
    dispatch({
      type: 'contentArticle/clearSelectKeys',
    })
    if (activeKey === '1') {
      dispatch({
        type: 'contentArticle/query',
      })
    } else if (activeKey === '2') {
      dispatch({
        type: 'contentArticle/getArticlePubModel',
      })
    }
  }

  return (
    <Page inner>
      <Tabs type="card" onChange={activeKey => handleTabsChange(activeKey)}>
        <Tabs.TabPane tab="已录入的文章" key="1">
          {/*查询*/}
          <ArticleFilter {...filterProps} />

          {/*临时按钮，选中数量大于0时，右上角显示常用按钮*/}
          {
            selectedRowKeys.length > 0 &&
            <Row style={{marginBottom: 24, textAlign: 'right', fontSize: 13}}>
              {/*发布、删除*/}
              <Col>
                {`选中 ${selectedRowKeys.length} 项 `}
                <Button type="primary" style={{marginLeft: 8}} onClick={onPub}>发布</Button>
                <Popconfirm title="是否确认删除？" placement="left" onConfirm={handleDeleteItems}>
                  <Button type="primary" style={{marginLeft: 8}}>删除</Button>
                </Popconfirm>
              </Col>
            </Row>
          }

          {/*表格主体*/}
          <ArticleTable {...listProps} />

          {/*弹出层，包括创建、修改*/}
          {/*{modalVisible && <ArticleModal {...modalProps} />}*/}
          {modalVisible && <ArticleModal {...modalProps} />}
          {/*弹出层，发布*/}
          {PubmodalVisible && <ArticlePubModal {...modalPubProps}  />}

        </Tabs.TabPane>
        <Tabs.TabPane tab="已发布的文章" key="2">
          {/*头部功能键*/}
          <ArticlePubFilter {...filterProps2}  />
          {/*临时按钮，选中数量大于0时，右上角显示常用按钮*/}
          {
            selectedRowKeysPub.length > 0 &&
            <Row style={{marginBottom: 24, textAlign: 'right', fontSize: 13}}>
              <Col>
                {`选中 ${selectedRowKeysPub.length} 项 `}
                <Popconfirm title="是否确认删除？" placement="left" onConfirm={handleDeletePubItems}>
                  <Button type="primary" style={{marginLeft: 8}}>删除</Button>
                </Popconfirm>
              </Col>
            </Row>
          }
          {/*表格*/}
          <ArticlePubTable {...listProps2} />
        </Tabs.TabPane>
      </Tabs>

    </Page>
  )

}

ContentArticle.propTypes = {
  contentArticle: PropTypes.object,
  location: PropTypes.object,
  dispatch: PropTypes.func,
  loading: PropTypes.object,
}

export default connect(({contentArticle, loading}) => ({contentArticle, loading}))(ContentArticle)
